import os
import re
from datetime import datetime

def get_safe_filename(filename):
    """获取安全的文件名，确保中文文件名和后缀名都被正确保留"""
    if not filename:
        return None
        
    # 分离文件名和后缀
    name, ext = os.path.splitext(filename)
    
    # 移除文件名中的非法字符，但保留中文字符
    name = re.sub(r'[<>:"/\\|?*]', '', name)
    
    # 添加时间戳
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    
    # 确保后缀名存在且为小写
    ext = ext.lower() if ext else ''
    
    # 组合新的文件名
    safe_filename = f"{name}_{timestamp}{ext}"
    
    return safe_filename

def get_file_size(file_path):
    """获取文件大小"""
    try:
        size = os.path.getsize(file_path)
        # 转换为人类可读格式
        for unit in ['B', 'KB', 'MB', 'GB']:
            if size < 1024.0:
                return f"{size:.1f} {unit}"
            size /= 1024.0
        return f"{size:.1f} TB"
    except OSError:
        return "0 B"

def check_file_type(filename):
    """检查文件类型"""
    allowed_extensions = {'doc', 'docx', 'pdf', 'txt', 'xls', 'xlsx', 'ppt', 'pptx'}
    return filename.lower().endswith(tuple(f'.{ext}' for ext in allowed_extensions))

def get_file_type(filename):
    """获取文件类型"""
    if not filename:
        return 'unknown'
    
    ext = filename.split('.')[-1].lower() if '.' in filename else ''
    
    # 文档类型映射
    type_map = {
        'doc': 'word',
        'docx': 'word',
        'xls': 'excel',
        'xlsx': 'excel',
        'ppt': 'powerpoint',
        'pptx': 'powerpoint',
        'pdf': 'pdf',
        'txt': 'text',
        'jpg': 'image',
        'jpeg': 'image',
        'png': 'image',
        'gif': 'image'
    }
    
    return type_map.get(ext, 'unknown')

def get_mime_type(filename):
    """获取文件的MIME类型"""
    if not filename:
        return 'application/octet-stream'
        
    ext = filename.split('.')[-1].lower() if '.' in filename else ''
    
    # MIME类型映射
    mime_map = {
        'pdf': 'application/pdf',
        'doc': 'application/msword',
        'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'xls': 'application/vnd.ms-excel',
        'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'ppt': 'application/vnd.ms-powerpoint',
        'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'txt': 'text/plain',
        'jpg': 'image/jpeg',
        'jpeg': 'image/jpeg',
        'png': 'image/png',
        'gif': 'image/gif'
    }
    
    return mime_map.get(ext, 'application/octet-stream')

def can_preview(filename):
    """检查文件是否支持预览"""
    ext = filename.split('.')[-1].lower() if '.' in filename else ''
    return ext in ['pdf', 'jpg', 'jpeg', 'png', 'gif', 'txt']

def ensure_upload_folder():
    """确保上传目录存在"""
    upload_folder = os.path.join(os.getcwd(), 'uploads')
    if not os.path.exists(upload_folder):
        os.makedirs(upload_folder)
    return upload_folder 